import React, {useState, useEffect} from 'react';
import {  message, TreeSelect } from 'antd';
import { getOrgTreeList } from '../service';

interface ParentOrgProps {
  defaultvalue:number;
  disabled:boolean;
  type:string;
  selectChange: (orgId:number,topOrgId:number) => void;
}
/**
 * 
 * 上级机构下拉控件
 */
const ParentOrgListComponent: React.FC<ParentOrgProps> = (props) => {

  const { defaultvalue, disabled, type, selectChange } = props;
  const [list, setList] = useState([]);
  const [refresh, handleRefresh] = useState<boolean>(true);

  useEffect(() => {
    if(refresh){
      handleRefresh(false);
      new Promise((resolve, reject) => {
        getOrgTreeList()
          .then((res) => {
            if (res && res.code === 200) {
              setList(res.data);
              resolve(true);
            } else {
              message.error('请求失败');
              resolve(false);
            }
          })
          .catch((error) => {
            message.error('请求失败');
            reject(error);
          });
      });
    }
  },[refresh]);

  return (
    <TreeSelect
      style={{ width: 200 }}
      allowClear
      disabled={disabled}
      defaultValue={defaultvalue>0?defaultvalue:null}
      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
      treeData={list}
      placeholder="请选择机构"
      treeDefaultExpandAll
      onChange={(value,label,extra) =>{
          if(type){
            if(type == "topOrgId"){
              if(extra.triggerNode){
                selectChange(value,extra.triggerNode.props.topOrgId);
              }else{
                selectChange("");
              }
            }else{
              selectChange(value)
            }
          }
        }
      }
      onFocus={() => handleRefresh(true)}
    />
  );
};

export default ParentOrgListComponent;
